package com.scisoft.scan.control.check;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.control.ScanHelper;
import com.scisoft.scan.data.BarCodeBean;
import com.scisoft.scan.data.PartBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.data.check.CheckDetailBean;
import com.scisoft.scan.data.check.CheckOrderBean;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper;
import com.scisoft.scan.ws.WebServiceHelper_Check;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

public class CheckDetailActivity extends Activity {

    private ImageView iv_Back; //返回按钮
    private ClearEditText et_bar;
    private TextView bt_all;
    private TextView bt_more;
    private TextView bt_less;
    private TextView bt_equal;
    private ListView lv_data;
    private View v_all;
    private View v_more;
    private View v_less;
    private View v_equal;
    private TextView tv_count;
    private TextView tv_checkCount;
    private View l_bottom;
    private List<CheckDetailBean> allDetailBeanList;//全部的查询结果列表
    private List<CheckDetailBean> currentDetailBeanList;//当前选中的过滤条件下的结果列表，来自allDetailBeanList和currentState
    private CheckOrderBean checkOrderBean;
    private String currentState;// 1 全部 2 盘盈 3 盘亏 4 盘平
    private String checkState;// 0 未审 1 已审
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//即隐藏标题栏
        setContentView(R.layout.activity_check_detail);
        //参数传递
        Intent intent = getIntent();
        //客户信息
        checkOrderBean = (CheckOrderBean) intent.getSerializableExtra("data");
        checkState = intent.getStringExtra("checkState");
        //初始化扫码
        init();
        //初始化控件
        et_bar = findViewById(R.id.et_bar);
        lv_data = findViewById(R.id.lv_data);
        lv_data.setOnItemClickListener(new ListViewClick());
        bt_all = findViewById(R.id.bt_all);
        bt_more = findViewById(R.id.bt_more);
        bt_less = findViewById(R.id.bt_less);
        bt_equal = findViewById(R.id.bt_equal);
        v_all = findViewById(R.id.v_all);
        v_more = findViewById(R.id.v_more);
        v_less = findViewById(R.id.v_less);
        v_equal = findViewById(R.id.v_equal);
        tv_count = findViewById(R.id.tv_count);
        tv_checkCount = findViewById(R.id.tv_checkCount);
        TextView tv_title = findViewById(R.id.tv_title);
        tv_title.setText("盘点清单[" + checkOrderBean.orderNo + "]");
        l_bottom = findViewById(R.id.l_bottom);
        if ("1".equals(checkState)) {
            l_bottom.setVisibility(View.GONE);
        } else {
            l_bottom.setVisibility(View.VISIBLE);
        }

        //页签切换
        bt_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_bar.setText("");
                setButton(v);
                BindData(CheckDetailActivity.this);
            }
        });
        bt_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_bar.setText("");
                setButton(v);
                BindData(CheckDetailActivity.this);
            }
        });
        bt_less.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_bar.setText("");
                setButton(v);
                BindData(CheckDetailActivity.this);
            }
        });
        bt_equal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_bar.setText("");
                setButton(v);
                BindData(CheckDetailActivity.this);
            }
        });
        setButton(bt_all);
        QueryData();

        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //审核
        TextView tv_submit = findViewById(R.id.tv_submit);
        tv_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹窗提醒
                int equal = 0;
                int all = allDetailBeanList.size();
                for (int i = 0; i < all; i++) {
                    if (allDetailBeanList.get(i).state.equals("4")) {//4代表盘平
                        equal++;
                    }
                }
                //判断记录数
                if (all > 0) {
                    if (equal != all) {
                        //如果盘点单有盘盈或者盘亏数据，需要计算账实相符率，弹窗要有确认或取消按钮。
                        double rate = (double) equal / (double) all;
                        BigDecimal bg = new BigDecimal(rate * 100);
                        double temp = bg.setScale(1, RoundingMode.HALF_UP).doubleValue();
                        //弹窗确认
                        AlertDialog alertDialog = new AlertDialog.Builder(CheckDetailActivity.this)
                                //.setTitle("这是标题")
                                .setMessage("账实相符率为" + String.valueOf(temp) + "%,是否继续审核?")
                                //.setIcon(R.mipmap.ic_launcher)
                                .setPositiveButton("是", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        AuditData();
                                    }
                                })
                                .setNegativeButton("否", new DialogInterface.OnClickListener() {//添加取消
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        finish();
                                    }
                                })
                                .create();
                        alertDialog.show();
                    } else {
                        //如果没有盘盈或盘亏数据，则不需要弹窗。
                        AuditData();
                    }
                } else {
                    Toast.makeText(CheckDetailActivity.this, "没有盘点记录无法审核", Toast.LENGTH_LONG).show();
                }
            }
        });

    }

    //设置tab页的颜色
    private void setButton(View v) {
        if (v.getId() == bt_all.getId()) {
            currentState = "1";//全部
            v_all.setVisibility(View.VISIBLE);
            v_more.setVisibility(View.INVISIBLE);
            v_less.setVisibility(View.INVISIBLE);
            v_equal.setVisibility(View.INVISIBLE);
            bt_all.setTextColor(getResources().getColor(R.color.tab_text_color_select));
            bt_more.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_less.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_equal.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
        } else if (v.getId() == bt_more.getId()) {
            currentState = "2";//盘盈
            v_all.setVisibility(View.INVISIBLE);
            v_more.setVisibility(View.VISIBLE);
            v_less.setVisibility(View.INVISIBLE);
            v_equal.setVisibility(View.INVISIBLE);
            bt_all.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_more.setTextColor(getResources().getColor(R.color.tab_text_color_select));
            bt_less.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_equal.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
        } else if (v.getId() == bt_less.getId()) {
            currentState = "3";//盘亏
            v_all.setVisibility(View.INVISIBLE);
            v_more.setVisibility(View.INVISIBLE);
            v_less.setVisibility(View.VISIBLE);
            v_equal.setVisibility(View.INVISIBLE);
            bt_all.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_more.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_less.setTextColor(getResources().getColor(R.color.tab_text_color_select));
            bt_equal.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
        } else {
            currentState = "4";//盘平
            v_all.setVisibility(View.INVISIBLE);
            v_more.setVisibility(View.INVISIBLE);
            v_less.setVisibility(View.INVISIBLE);
            v_equal.setVisibility(View.VISIBLE);
            bt_all.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_more.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_less.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_equal.setTextColor(getResources().getColor(R.color.tab_text_color_select));
        }
    }
    //弹窗输入
    private class ListViewClick implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //非审核才能弹出
            if (!"1".equals(checkState)) {
                if (position >= 0 && position < currentDetailBeanList.size()) {
                    CheckDetailBean checkDetailBean = currentDetailBeanList.get(position);
                    alert_edit(checkDetailBean);
                }
            }
        }
    }
    //自定义弹出窗口
    private void alert_edit(final CheckDetailBean checkDetailBean) {
        //1.创建一个Dialog对象,去除标题栏
        final Dialog mDialog = new Dialog(this);
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //2.填充布局,将自定义布局设置进去
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.dialog_check, null);
        mDialog.setContentView(dialogView);
        //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        Window window = mDialog.getWindow();
        lp.copyFrom(window.getAttributes());
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
        mDialog.show();
        window.setAttributes(lp);

        //4、设置点击其它地方不让消失弹窗
        mDialog.setCancelable(false);
        //5、初始化控件
        TextView tv_zms = (TextView) dialogView.findViewById(R.id.tv_zms);
        tv_zms.setText(String.valueOf(checkDetailBean.allCount));
        final TextView et_count = (TextView) dialogView.findViewById(R.id.et_count);
        TextView tv_equal = (TextView) dialogView.findViewById(R.id.tv_equal);
        tv_equal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //盘平
                et_count.setText(String.valueOf(checkDetailBean.allCount));
                CheckDetailBean newData = checkDetailBean;
                newData.checkCount = et_count.getText().toString();
                SubmitData(newData);
                mDialog.dismiss();
            }
        });
        TextView tv_none = (TextView) dialogView.findViewById(R.id.tv_none);
        tv_none.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //盘无
                et_count.setText("0");
                CheckDetailBean newData = checkDetailBean;
                newData.checkCount = et_count.getText().toString();
                SubmitData(newData);
                mDialog.dismiss();
            }
        });
        TextView tv_ok = (TextView) dialogView.findViewById(R.id.tv_ok);
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //按下确定键后的事件
                CheckDetailBean newData = checkDetailBean;
                newData.checkCount = et_count.getText().toString();
                SubmitData(newData);
                mDialog.dismiss();
            }
        });
        TextView tv_cancel = (TextView) dialogView.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
    }
    //查询数据
    private void QueryData(){
        CommonUtil.showPress(CheckDetailActivity.this);
        QueryTask queryTask = new QueryTask(CheckDetailActivity.this);
        queryTask.execute();
    }
    //统计数据
    private void StatisticsData() {
        int more = 0;
        int less = 0;
        int equal = 0;
        int not = 0;
        int all = allDetailBeanList.size();
        for (int i = 0; i < all; i++) {
            if (allDetailBeanList.get(i).state.equals("3")) {//3代表盘盈
                more++;
            } else if (allDetailBeanList.get(i).state.equals("5")) {//5代表盘亏
                less++;
            } else if (allDetailBeanList.get(i).state.equals("4")) {//4代表盘平
                equal++;
            } else if (allDetailBeanList.get(i).state.equals("1")) {//4代表未盘
                not++;
            }
        }
        bt_all.setText("全部[" + all + "]");
        bt_more.setText("盘盈[" + more + "]");
        bt_less.setText("盘亏[" + less + "]");
        bt_equal.setText("盘平[" + equal + "]");
        tv_count.setText(String.valueOf(all - not));
        tv_checkCount.setText(String.valueOf(not));
    }
    //绑定数据
    private void BindData(Context context) {
        //过滤：注意一定是传地址的方式才能这样进行两个列表的过滤，两个列表的每个元素的地址相同
        currentDetailBeanList = new ArrayList<>();
        if (allDetailBeanList != null) {
            for (int i = 0; i < allDetailBeanList.size(); i++) {
                if (currentState.equals("1")) {
                    //1 全部
                    currentDetailBeanList.add(allDetailBeanList.get(i));
                } else if (currentState.equals("2")) {
                    //2 盘盈
                    if (allDetailBeanList.get(i).state.equals("3")) {//3代表盘盈
                        currentDetailBeanList.add(allDetailBeanList.get(i));
                    }
                } else if (currentState.equals("3")) {
                    //3 盘亏
                    if (allDetailBeanList.get(i).state.equals("5")) {//5代表盘亏
                        currentDetailBeanList.add(allDetailBeanList.get(i));
                    }
                } else if (currentState.equals("4")) {
                    //4 盘平
                    if (allDetailBeanList.get(i).state.equals("4")) {//4代表盘平
                        currentDetailBeanList.add(allDetailBeanList.get(i));
                    }
                }
            }
        }
        StatisticsData();
        //绑定数据
        CheckDetailAdapter adapter = new CheckDetailAdapter(currentDetailBeanList, context);
        lv_data.setAdapter(adapter);
    }
    //扫描排序（扫描到的排到第一行）
    private void BindDataOrder(Context context, PartBean partBean) {
        //扫描默认到全部页
        setButton(bt_all);
        //过滤：注意一定是传地址的方式才能这样进行两个列表的过滤，两个列表的每个元素的地址相同
        currentDetailBeanList = new ArrayList<>();
        if (allDetailBeanList != null) {
            for (int i = 0; i < allDetailBeanList.size(); i++) {
                CheckDetailBean checkDetailBean = allDetailBeanList.get(i);
                if (partBean.partCode.equals(checkDetailBean.partCode)) {
                    currentDetailBeanList.add(0, checkDetailBean);
                } else {
                    currentDetailBeanList.add(checkDetailBean);
                }
            }
        }
        StatisticsData();
        //绑定数据
        CheckDetailAdapter adapter = new CheckDetailAdapter(currentDetailBeanList, context);
        lv_data.setAdapter(adapter);
    }
    //查询服务
    class QueryTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                allDetailBeanList = WebServiceHelper_Check.CHECK_02(checkOrderBean.orderId);
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }
    //盘点数据
    private void SubmitData(CheckDetailBean newData) {
        CommonUtil.showPress(CheckDetailActivity.this);
        SubmitTask submitTask = new SubmitTask(CheckDetailActivity.this, newData);
        submitTask.execute();
    }
    //盘点服务
    class SubmitTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private CheckDetailBean checkDetailBean;
        SubmitTask(Context context,CheckDetailBean checkDetailBean) {
            super();
            mcontext = context;
            this.checkDetailBean = checkDetailBean;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_Check.CHECK_03(checkDetailBean);
                allDetailBeanList = WebServiceHelper_Check.CHECK_02(checkOrderBean.orderId);
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }finally {
                try {
                    //check_03报错，这里也走了，但是界面没刷新， 当盘点数输入字母，后台返回错误信息
                    allDetailBeanList = WebServiceHelper_Check.CHECK_02(checkOrderBean.orderId);
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                Toast.makeText(getApplicationContext(),  "提交成功", Toast.LENGTH_LONG).show();
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(),  msg, Toast.LENGTH_LONG).show();
            }
        }
    }
    //审核数据
    private void AuditData() {
        CommonUtil.showPress(CheckDetailActivity.this);
        AuditTask auditTask = new AuditTask(CheckDetailActivity.this);
        auditTask.execute();
    }
    //审核服务
    class AuditTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        AuditTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_Check.CHECK_04(checkOrderBean.orderId);
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                Toast.makeText(getApplicationContext(),  "提交成功", Toast.LENGTH_LONG).show();
                finish();
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //region 扫码相关

    //扫码处理
    private void ScanData(String barCode) throws Exception {
        if (barCode != null && barCode.length() > 0) {
            CommonUtil.showPress(this);
            QueryBarCodeTask queryBarCodeTask = new QueryBarCodeTask(CheckDetailActivity.this, barCode);
            queryBarCodeTask.execute();
        }
    }

    //查询条码服务，排序
    class QueryBarCodeTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String barCode;
        private BarCodeBean barCodeBean = null;

        QueryBarCodeTask(Context context, String barCode) {
            super();
            mcontext = context;
            this.barCode = barCode;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                barCodeBean = WebServiceHelper.ParseBarCode(barCode);
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                if (barCodeBean == null || barCodeBean.barType == BarCodeBean.BAR_UNKNOWN) {
                    Toast.makeText(getApplicationContext(), msg = "无效二维码：" + barCode, Toast.LENGTH_LONG).show();
                } else if (barCodeBean.partBean != null) {
                    //排序
                    BindDataOrder(getApplicationContext(), barCodeBean.partBean);
                } else {
                    Toast.makeText(getApplicationContext(), msg = "未查询到配件", Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //初始化
    private void init() {
        //初始化Profile
        ScanHelper.CreateProfile(this);
        //设置广播消息的接收器
        registerReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    //注册广播
    private void registerReceiver() {
        //IntentFilter intFilter = new IntentFilter(ScanManager.ACTION_SEND_SCAN_RESULT);
        //registerReceiver(mResultReceiver, intFilter);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ScanHelper.ACTION_RESULT_NOTIFICATION);   // for notification result
        filter.addAction(ScanHelper.ACTION_RESULT);                // for error code result
        filter.addCategory(Intent.CATEGORY_DEFAULT);    // needed to get version info
        filter.addAction(ScanHelper.ACTION_SCAN_OUTPUT); // register to received broadcasts via DataWedge scanning
        registerReceiver(mResultReceiver, filter);
    }

    //取消注册广播
    private void unRegisterReceiver() {
        try {
            unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
            Toast.makeText(this, "注销扫码失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    //监听扫码数据的广播，当设置广播输出时作用该方法获取扫码数据
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ScanHelper.ACTION_SCAN_OUTPUT)) {
                // 处理扫码结果
                try {
                    String decodedData = intent.getStringExtra("com.symbol.datawedge.data_string");
                    et_bar.setText(decodedData);
                    ScanData(decodedData);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(CheckDetailActivity.this, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };
    //endregion

}
